﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using RTUDataAcquisition.AppCode;

namespace RTUDataAcquisition
{
    public partial class ServerSetting : Form
    {
        public ServerSetting()
        {
            InitializeComponent();
        }

        private void ServerSetting_Load(object sender, EventArgs e)
        {
            try
            {
                txtIp.Text = INIConfig.IpAddress;
                nudPort.Value = Convert.ToInt32(INIConfig.IpPort);
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog(ex, "获取服务器设置失败!");
            }
        }

        /// <summary>
        /// 获取本机IP
        /// </summary>
        private void linkIp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址，AddressFamily.InterNetwork表示此IP为IPv4
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                           txtIp.Text = IpEntry.AddressList[i].ToString();
                           break;
                    }
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog(ex, "获取本机IP失败!");
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtIp.Text.Trim() == string.Empty)
                {
                    Messages.ShowMessage("请输入服务器IP!");
                    return;
                }

                //验证IP正确性
                if (!Common.CheckIP(txtIp.Text.Trim()))
                {
                    Messages.ShowMessage("请输入正确的IP地址!");
                    return;
                }

                INIFile.WriteObject("monitor", "IpAddress", txtIp.Text.Trim());
                INIFile.WriteObject("monitor", "IpPort", nudPort.Value);
                INIConfig.LoadSettings();
                Messages.ShowMessage("保存成功!");
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog(ex, "保存服务器设置失败!");
            }
        }
    }
}
